import { config } from '../../../../api/config'
import { SignInFormValues } from '../../../../components/forms/signInForm'
import { SignUpFormValues } from '../../../../components/forms/signUpForm'
import { TUser } from '../../../types'
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'

type TUserAuthResponse = {
	data: TUser
	token: string
}

export const apiSlice = createApi({
	reducerPath: 'apiSlice',
	baseQuery: fetchBaseQuery({
		baseUrl: config.apiUrl,
		// prepareHeaders: (headers, { getState }) => {
		// 	const token = (getState() as RootState)?.user?.token
		// 	if (token) {
		// 		headers.set('Authorization', `Bearer ${token}`)
		// 	}
		// 	return headers
		// },
	}),
	tagTypes: ['Auth'],
	endpoints: (builder) => ({
		signIn: builder.mutation<TUserAuthResponse, SignInFormValues>({
			query: (authUser) => ({
				url: '/signin',
				method: 'POST',
				body: authUser,
			}),
			// providesTags: ['Auth'],
		}),
		// регистрация
		signUp: builder.mutation<TUser, SignUpFormValues>({
			query: (userAuth) => ({
				url: '/signup',
				method: 'POST',
				body: userAuth,
			}),
			// invalidatesTags: ['Auth'],
		}),
	}),
})

export const { useSignInMutation, useSignUpMutation } = apiSlice
